//
//  ToolHelper.swift
//  d11
//
//  Created by peale on 2018/8/2.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import Countly
var ipAddress = ""
class ToolHelper{
    static func statisticsPage(pageName : String){
        var dict : Dictionary<String, String> =  Dictionary<String, String>.init()
        let userName = UserDefaults.standard.string(forKey:  DefaultKey.USER_LOGIN_NAME)
        if UserHelper.getLoginStatus() {
             dict["用户名"] = userName ?? "未知"
        }else{
             dict["用户名"] = "游客"
        }
        dict["IP访问量"] = ipAddress
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
        dict["版本号"] = currentVersion as? String ?? ""
        Countly.sharedInstance().recordEvent(pageName, segmentation:dict)
       
    }
    static func statisticsPageWithInterface(pageName:String,statusCode:String,kzingStatusCode:String,errorResponse:String){
        var dict : Dictionary<String, String> =  Dictionary<String, String>.init()
        let userName = UserDefaults.standard.string(forKey:  DefaultKey.USER_LOGIN_NAME)
        if UserHelper.getLoginStatus() {
            dict["用户名"] = userName ?? "未知"
        }else{
            dict["用户名"] = "游客"
        }
        dict["IP访问量"] = ipAddress
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
        dict["版本号"] = currentVersion as? String ?? ""
        dict["domain"]  = UserDefaults.standard.value(forKey: DefaultKey.USER_DOMAIN) as? String ?? ""
        dict["errorResponse"] = errorResponse
        dict["kzingStatusCode"] = kzingStatusCode
        dict["statusCode"] = statusCode
        Countly.sharedInstance().recordEvent(pageName, segmentation:dict)
    }
    static func statisticsPageWithGameName(pageName : String,gameName:String?){
        var dict : Dictionary<String, String> =  Dictionary<String, String>.init()
        let userName = UserDefaults.standard.string(forKey:  DefaultKey.USER_LOGIN_NAME)
        if UserHelper.getLoginStatus() {
            dict["用户名"] = userName ?? "未知"
        }else{
            dict["用户名"] = "游客"
        }
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"]
        dict["版本号"] = currentVersion as? String ?? ""
        dict["游戏名称"] = gameName
        Countly.sharedInstance().recordEvent(pageName, segmentation:dict)
    }
   static func imageWithColor(color:UIColor,size:CGSize) ->UIImage{
        let rect = CGRect(x:0, y:0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context  = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    //不确定类型json字段转String 金额
    static func jsonValueToString(value:Any)->String{
        if value is String {
            let tempVal =  value as! String
            if tempVal.count > 0{
                print("字符串\(tempVal)")
                return String(format: "%.2f",Double(tempVal)!)
            }else{
                return "0.00"
            }
        }else if value is Int {
            let tempVal = value as! Int
            print("整型\(tempVal)")
            if tempVal >= 0 {
                return String(format: "%.2f", Double(tempVal))
            }else{
                return "0.00"
            }
        }else if value is Double {
            let tempVal =  value as! Double
            print("double型\(tempVal)")
            if tempVal >= 0{
                return String(format: "%.2f", tempVal)
            }else{
                return "0.00"
            }
        }
        return "读取失败!"
    }
    //时间戳转日期 字符串
    static func timeStampToDateString(timeStamp:String)->Date{
        let timeInterval:TimeInterval =  TimeInterval(timeStamp)!
     //   let date =  Date(timeIntervalSince1970: timeInterval)
        let date = Date()
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        print("对应的日期时间：\(dformatter.string(from: date))")
        return date
    }
    
    //时间戳转日期 date
    static func timeStampToDate(timeStamp:String)->String{
        let timeInterval:TimeInterval =  TimeInterval(timeStamp)!
        let date =  Date(timeIntervalSince1970: timeInterval)
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        print("对应的日期时间：\(dformatter.string(from: date))")
        return dformatter.string(from: date)
    }
    
    //判断是否是数字
   static func isPurnFloat(string: String) -> Bool {
        
        let scan: Scanner = Scanner(string: string)
        
        var val:Float = 0
        
        return scan.scanFloat(&val) && scan.isAtEnd
    }
    
     // 获取顶层控制器 根据window
  static  func getTopVC() -> (UIViewController?) {
        var window = UIApplication.shared.keyWindow
        //是否为当前显示的window
        if window?.windowLevel != UIWindow.Level.normal{
            let windows = UIApplication.shared.windows
            for  windowTemp in windows{
            if windowTemp.windowLevel == UIWindow.Level.normal{
                window = windowTemp
                break
                }
            }
        }
      let vc = window?.rootViewController
      return getTopVC(withCurrentVC: vc)
     }
      ///根据控制器获取 顶层控制器
  static  func getTopVC(withCurrentVC VC :UIViewController?) -> UIViewController? {
     if VC == nil {
        print("🌶： 找不到顶层控制器")
        return nil
    }
     if let presentVC = VC?.presentedViewController {
        //modal出来的 控制器
        return getTopVC(withCurrentVC: presentVC)
    }else if let tabVC = VC as? UITabBarController {
      // tabBar 的跟控制器
        if let selectVC = tabVC.selectedViewController {
          return getTopVC(withCurrentVC: selectVC)
        }
        return nil
    } else if let naiVC = VC as? UINavigationController {
      // 控制器是 nav
        return getTopVC(withCurrentVC:naiVC.visibleViewController)
      } else {
      // 返回顶控制器
      return VC
      }
    }
}
